package com.wulwu.permission.config;

import com.wulwu.permission.entity.PermissionMenuInfo;
import com.wulwu.permission.entity.PermissionMenuInfoExample;
import com.wulwu.permission.filter.JWTAuthenticationEntryPoint;
import com.wulwu.permission.filter.JWTLoginFilter;
import com.wulwu.permission.filter.JWTValidationFilter;
import com.wulwu.permission.mapper.PermissionMenuInfoMapper;
import com.wulwu.permission.service.SecurityUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

/**
 * @Description
 * @Author Major
 * @Date 2020/11/24 16:23
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityUserDetailService securityUserDetailService;

    @Autowired
    private PermissionMenuInfoMapper permissionMenuInfoMapper;

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //添加授权账户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置用户账号信息和权限
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*http协议认证 前后端分离 采用 JWT 令牌*/
        PermissionMenuInfoExample permissionMenuInfoExample = new PermissionMenuInfoExample();
        permissionMenuInfoExample.createCriteria().andFlagEqualTo(1);
        List<PermissionMenuInfo> permissionList = permissionMenuInfoMapper.selectByExample(permissionMenuInfoExample);
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http.authorizeRequests();
        permissionList.forEach(e -> {
            urlRegistry.antMatchers(e.getmUrl()).hasAnyAuthority(e.getPermission());
        });
        urlRegistry.antMatchers("/api/login").permitAll()
                .antMatchers("/**").fullyAuthenticated()
                .and()
                .addFilter(new JWTValidationFilter(authenticationManager()))
                .addFilter(new JWTLoginFilter(authenticationManager())).csrf().disable()
                //关闭 session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //异常处理
                .exceptionHandling()
                //匿名用户访问无权限资源时的异常
                .authenticationEntryPoint(new JWTAuthenticationEntryPoint());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        //实现 捕获 UserNotFoundExceptions
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(securityUserDetailService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return daoAuthenticationProvider;
    }
}

